package logic

import (
	"context"
	"fmt"
	"house/cache"
	"house/models"
	"time"

	"house/houserpc/houserpc"
	"house/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CommentListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCommentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommentListLogic {
	return &CommentListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CommentListLogic) CommentList(in *houserpc.CommentListRequest) (*houserpc.CommentListResponse, error) {
	// todo: add your logic here and delete this line
	var house models.HouseData
	models.DB.Table("houses").Debug().
		Select("houses.*,classes.name as class_name,users.nick_name as user_name").
		Joins("left join classes on classes.id=houses.class_id").
		Joins("left join users on users.id=houses.user_id").
		Joins("left join comments on comments.house_id=houses.id").
		Order("created_at").
		Where("house_id=?", in.HouseId).
		Find(&house)
	var comments []models.Comment
	models.DB.Find(&comments)
	var commentList []*houserpc.CommentList
	for _, comment := range comments {
		list := houserpc.CommentList{
			Context:   comment.Context,
			UserId:    int64(comment.UserId),
			HouseId:   int64(comment.HouseId),
			LikeCount: int64(comment.LikeCount),
		}
		commentList = append(commentList, &list)
		if comment.LikeCount >= 1000 {
			cache.Rdb.Set(l.ctx, "comment", comment.Context, time.Minute*15)
		}
	}
	fmt.Println(commentList)

	return &houserpc.CommentListResponse{
		Title:        house.Title,
		Price:        float32(house.Price),
		Context:      house.Context,
		UserName:     house.UserName,
		ClassName:    house.ClassName,
		CollectCount: int64(house.CollectCount),
		List:         commentList,
	}, nil
}
